import { Image } from 'antd'
import { useEffect, useState } from 'react'
import { FilePreviewState } from '../constants'

function PictureViewer({ configProps, setLoading, handleError }: FilePreviewState) {
  const [show, setShow] = useState(false)
  const [imageUrl, setImageUrl] = useState(null)
  useEffect(() => {
    // minio迁移到sso
    fetch(configProps.fileUrl)
      // fetch(`/api/v1/knowledge/download?file_path=${configProps.fileUrl}`)
      .then(response => {
        if (response.ok) {
          return response.blob()
        } else {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
      })
      .then(blob => {
        if (blob) {
          const url = URL.createObjectURL(blob)
          setImageUrl(url)
          setShow(true)
        }
      })
      .catch(error => {
        console.error('加载文本文件出错:', error)
        handleError(`${configProps.title}文件加载失败`)
      })
      .finally(() => {
        setLoading(false)
      })
  }, [configProps])
  return (
    <>
      {show && (
        <Image
          // src={imageUrl}
          width={0}
          height={0}
          alt={configProps.title}
          preview={{
            visible: true,
            src: imageUrl,
            getContainer: false,
            mask: <></>,
            closeIcon: <></>,
            destroyOnClose: true
          }}
          onLoad={() => setLoading(false)}
          onError={() => handleError(`${configProps.title}图片加载失败`)}
        />
      )}
    </>
  )
}

export default PictureViewer
